from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog, QTabWidget
from PyQt5.QtGui import QPixmap, QImage
from Load_Demo import Ui_Load_lineEdit
import sqlite3
import re
from tkinter import *
import os
from fileopen import Ui_MainWindow
from ui_MainWindow2 import Ui_MainWindow2

# 数据库--------------------------------
# from Wenjianjia import app
USER_PWD = {
    'la_vie': 'password', 'user1': '1234'
}
print(USER_PWD)
cx = sqlite3.connect("user_data3.db")
cu = cx.cursor()
user_name = cu.execute("select name from user WHERE id = 1").fetchall()
user_password = cu.execute("select password from user WHERE id = 1").fetchall()
user_password = user_password[0]
user_name = user_name[0]
user_password = str(user_password)
user_name = str(user_name)
# 对字符穿进行去除杂志
# user_password=''.join(user_password)
clear = '[,()"]'
user_password = re.sub(clear, '', user_password)
user_name = re.sub(clear, '', user_name)
user_name = eval(user_name)
user_password = eval(user_password)
USER_PWD2 = {
    'la_vie': 'password', user_name: user_password
}


# user_password=''.join(user_password)
# print(user_name)
# print(user_password)
# print(USER_PWD2)
# -------------------------------------------------


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.actionfileopen.triggered.connect(self.open_file)
        # self.xinAction.triggered.connect(self.xin_file)
        exitAction = QAction(QIcon('exit.png'), 'Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(qApp.quit)

        self.toolbar = self.addToolBar('Exit')
        self.toolbar.addAction(exitAction)

        self.setGeometry(300, 300, 800, 500)
        self.setWindowTitle('主界面')
        # ----------------------C
        button2 = QPushButton("C语言", self)
        # self.QPushButton.setGeometry(QtCore.QRect(345, 500, 151, 46))
        button2.clicked.connect(self.show_child)
        button2.setGeometry(500, 100, 100, 40)
        self.child_window = Child()
        # -------------------J
        button = QPushButton("JAVA语言", self)
        # self.QPushButton.setGeometry(QtCore.QRect(345, 500, 151, 46))
        button.clicked.connect(self.show2_child)
        button.setGeometry(500, 200, 100, 40)
        self.child2_window = MainWidget()
        # ----------------------------
        self.centralwidget = QtWidgets.QWidget()
        self.centralwidget.setObjectName("centralwidget")
        # 设置小框道德按钮和事件
        # 文件名称----------------------------
        self.QLabl = QLabel(self)
        self.QLabl.setText("文件名称")
        self.QLabl.setGeometry(0, 100, 400, 38)

        self.QLablEdit = QLineEdit(self)
        self.QLablEdit.textChanged.connect(self.bn_changed)
        self.QLablEdit.setGeometry(0, 140, 400, 38)
        # ------------------------------------------------------

        # JAV C选项
        self.QLab3 = QLabel(self)
        self.QLab3.setText("文件类型")
        self.QLab3.setGeometry(50, 300, 400, 38)
        self.rb11 = QRadioButton('JAVA', self)
        self.rb11.setGeometry(50, 350, 400, 38)
        self.rb12 = QRadioButton('C', self)
        self.rb12.setGeometry(50, 400, 400, 38)

        self.QLab4 = QLabel(self)
        self.QLab4.setText("文件等级")
        self.QLab4.setGeometry(150, 300, 400, 38)
        self.rb21 = QRadioButton('A', self)
        self.rb21.setGeometry(150, 350, 400, 38)
        self.rb22 = QRadioButton('B', self)
        self.rb22.setGeometry(150, 400, 400, 38)
        self.rb23 = QRadioButton('C', self)
        self.rb23.setGeometry(150, 450, 400, 38)

        # bt1 = QPushButton('提交', self)
        # bt1.setGeometry(300, 100, 400, 38)
        # 为节省行数，部分非重要代码省略...

        self.bg1 = QButtonGroup(self)
        self.bg1.addButton(self.rb11, 11)
        self.bg1.addButton(self.rb12, 12)

        self.bg2 = QButtonGroup(self)
        self.bg2.addButton(self.rb21, 21)
        self.bg2.addButton(self.rb22, 22)
        self.bg2.addButton(self.rb23, 23)

        self.info1 = ''
        self.info2 = ''

        self.bg1.buttonClicked.connect(self.rbclicked)
        self.bg2.buttonClicked.connect(self.rbclicked)
        # bt1.clicked.connect(self.submit)

        # self.show()

        # 文件路径------------------------------------------------
        self.button = QPushButton('选取文件', self)
        self.button.clicked.connect(self.open_file2)
        self.button.setGeometry(0, 200, 100, 40)
        self.button.setObjectName("file")

        self.buttonEdit = QPushButton('', self)
        self.buttonEdit.setGeometry(QtCore.QRect(0, 250, 480, 28))
        self.buttonEdit.setObjectName("file")
        self.buttonEdit.setStyleSheet(" margin: 0px; padding: 0px;")
        # ---------------------------------------------------------------
        # 写入的的文件名，文件路径
        self.QLabl.File = ""
        self.button.File_path = ""
        # queding------------------------
        self.button2 = QPushButton('确定', self)
        self.button2.clicked.connect(self.submit)
        self.button2.clicked.connect(self.bn_queding)
        self.button2.setGeometry(300, 400, 100, 40)
        # 取消--------------------------------------
        self.button3 = QPushButton('取消', self)
        self.button3.clicked.connect(self.bn_quxiao)
        self.button3.setGeometry(300, 450, 100, 40)
        # -------------------------------------------

    def submit(self):
        if self.info1 == '' or self.info2 == '':
            QMessageBox.information(self, 'What?', '貌似有没有选的啊，快去选一个吧！')
        else:
            QMessageBox.information(self, '文件类型', '文件类型:' + self.info1 + ',' + '文件等级:' + self.info2)
            print(self.QLabl.File)
            print(self.info1)
            print(self.info2)
            print("简介")
            cx = sqlite3.connect("user_data3.db")
            cu = cx.cursor()
            input_mingcheng = self.QLabl.File
            input_leixing = self.info1
            input_dengji = self.info2
            input_jianjie = "简介"
            sql = sqlite3.connect("JAVAshujuku.db")
            sql.execute("insert into user(softname,softtype,softdj,softjj) values(?,?,?,?)",
                        (input_mingcheng, input_leixing, input_dengji, input_jianjie))
            sql.commit()
            # softname = cu.execute("select name from user WHERE id = 1").fetchall()
            # softtype = cu.execute("select password from user WHERE id = 1").fetchall()
            # softdj = cu.execute("select name from user WHERE id = 1").fetchall()
            # softjj = cu.execute("select password from user WHERE id = 1").fetchall()

    def rbclicked(self):
        sender = self.sender()
        if sender == self.bg1:
            if self.bg1.checkedId() == 11:
                self.info1 = 'JAVA'
            elif self.bg1.checkedId() == 12:
                self.info1 = 'C'

            else:
                self.info1 = ''
        else:
            if self.bg2.checkedId() == 21:
                self.info2 = 'A'
            elif self.bg2.checkedId() == 22:
                self.info2 = 'B'
            elif self.bg2.checkedId() == 23:
                self.info2 = 'C'
            else:
                self.info2 = ''
        # ----------------------------

    def open_file2(self):
        fileName = QtWidgets.QFileDialog.getExistingDirectory(None, "选取文件", os.getcwd())
        self.buttonEdit.setText(fileName)
        self.button.File_path = fileName

    def bn_changed(self):
        self.QLabl.File = self.QLablEdit.text()

    def bn_queding(self):
        path = os.getcwd()
        path = path + "/uploads"
        if not os.path.exists(path):
            os.makedirs(os.path.join(self.button.File_path, self.QLabl.File, "软件代码"))
            os.makedirs(os.path.join(self.button.File_path, self.QLabl.File, "软件缺陷"))
            os.makedirs(os.path.join(self.button.File_path, self.QLabl.File, "软件缺陷", "度量文件夹"))
            os.makedirs(os.path.join(self.button.File_path, self.QLabl.File, "软件缺陷", "缺陷文件夹"))
            os.makedirs(os.path.join(self.button.File_path, self.QLabl.File, "软件缺陷", "大数据文件夹"))

            os.makedirs(os.path.join(self.button.File_path, self.QLabl.File, "系统分析阶段"))
            os.makedirs(os.path.join(self.button.File_path, self.QLabl.File, "软件需求阶段"))
            os.makedirs(os.path.join(self.button.File_path, self.QLabl.File, "软件设计阶段"))
            os.makedirs(os.path.join(self.button.File_path, self.QLabl.File, "软件实现阶段"))
            os.makedirs(os.path.join(self.button.File_path, self.QLabl.File, "软件测试阶段"))
            os.makedirs(os.path.join(self.button.File_path, self.QLabl.File, "软件评审交付阶段"))
            os.makedirs(os.path.join(self.button.File_path, self.QLabl.File, "软件使用维护阶段"))

    def bn_quxiao(self):
        self.close()

        self.show()

    def show_child(self):
        self.child_window.show()

    def show2_child(self):
        self.child2_window.show()

    def open_file(self):
        fileName, fileType = QtWidgets.QFileDialog.getOpenFileName(self, "选取文件", os.getcwd(),
                                                                   "E:/Renwu/20220411APP/登陆界面设计")
        print(fileName)
        print(fileType)


from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel, QSqlQueryModel


# --------------------------C------小窗口
class Child(QWidget):
    def __init__(self, parent=None):
        super(Child, self).__init__(parent)
        # 声明数据库连接


# JAVA主页面设计--------------------------------------
class MainWidget(QWidget):

    def __init__(self, parent=None):
        super(MainWidget, self).__init__(parent)
        self.setWindowTitle("我是java程序窗口")
        self.resize(12900, 11600)
        # self.showMaximized()
        # 获取系统所有文件-------------树形结构------------------
        self.model01 = QFileSystemModel()
        # 进行筛选只显示文件夹，不显示文件和特色文件
        self.model01.setFilter(QtCore.QDir.Dirs | QtCore.QDir.NoDotAndDotDot)
        self.model01.setRootPath("E:/Renwu/20220411APP/登陆界面设计/测试")

        # 定义创建左边窗口
        self.treeView1 = QTreeView(self)
        self.treeView1.setModel(self.model01)
        self.treeView1.setGeometry(0, 150, 450, 550)
        for col in range(1, 4):
            self.treeView1.setColumnHidden(col, True)
        self.treeView1.doubleClicked.connect(self.initUI)
        # 数据库文件介绍---------------------------------------------

        # 声明数据库连接
        self.db = None
        # 布局管理器
        self.layout = QVBoxLayout()
        # 查询模型
        self.queryModel = QSqlQueryModel()
        # 表格视图
        self.QLabl = QLabel(self)
        # self.QLabl.setText("项目数据")
        self.tableView = QTableView()
        self.tableView.setModel(self.queryModel)
        self.tableView.setGeometry(300, 150, 450, 550)
        #
        self.totalPageLabel = QLabel()
        # self.currentPageLabel = QLabel()
        self.switchPageLineEdit = QLineEdit()
        self.prevButton = QPushButton("Prev")
        # self.prevButton.setGeometry(300, 150, 450, 550)
        self.nextButton = QPushButton("Next")
        # self.switchPageButton = QPushButton("Switch")
        # 当前页
        # self.currentPage = 1
        # 总页数
        self.totalPage = None
        # 总记录数
        self.totalRecordCount = None
        # 每页记录数
        self.pageRecordCount = 4

        self.initUI1()
        self.initializedModel()
        self.setUpConnect()
        self.updateStatus()

    # ---------------------------------------------------------
    def initUI1(self):
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.tableView.setMaximumHeight(100)

        self.layout.addWidget(self.tableView)

        hLayout = QHBoxLayout()

        self.switchPageLineEdit.setFixedWidth(40)

        hLayout.addWidget(self.totalPageLabel)
        hLayout.addStretch(1)

        self.layout.addLayout(hLayout)
        self.setLayout(self.layout)

    def setUpConnect(self):
        self.prevButton.clicked.connect(self.onPrevPage)
        self.nextButton.clicked.connect(self.onNextPage)

    def initializedModel(self):
        self.db = QSqlDatabase.addDatabase("QSQLITE")
        self.db.setDatabaseName("JAVAshujuku.db")
        if not self.db.open():
            return False
        self.queryModel.setHeaderData(0, Qt.Horizontal, "id")
        self.queryModel.setHeaderData(1, Qt.Horizontal, "softname1")
        self.queryModel.setHeaderData(2, Qt.Horizontal, "softtype")
        self.queryModel.setHeaderData(3, Qt.Horizontal, "softdj")
        self.queryModel.setHeaderData(4, Qt.Horizontal, "softjj")
        # 获取表的所有记录数
        sql = "SELECT * FROM user"
        self.queryModel.setQuery(sql, self.db)
        self.totalRecordCount = self.queryModel.rowCount()
        if self.totalRecordCount % self.pageRecordCount == 0:
            self.totalPage = self.totalRecordCount / self.pageRecordCount
        else:
            self.totalPage = int(self.totalRecordCount / self.pageRecordCount) + 1
        # 显示第1页
        sql = "SELECT * FROM user limit %d,%d" % (0, self.pageRecordCount)
        self.queryModel.setQuery(sql, self.db)

    def onPrevPage(self):
        self.updateStatus()

    def onNextPage(self):
        self.updateStatus()

    def onSwitchPage(self):
        szText = self.switchPageLineEdit.text()
        pattern = re.compile('^[0-9]+$')
        match = pattern.match(szText)
        if not match:
            QMessageBox.information(self, "提示", "请输入数字.")
            return
        if szText == "":
            QMessageBox.information(self, "提示", "请输入跳转页面.")
            return
        pageIndex = int(szText)
        if pageIndex > self.totalPage or pageIndex < 1:
            QMessageBox.information(self, "提示", "没有指定的页，清重新输入.")
            return

        limitIndex = (pageIndex - 1) * self.pageRecordCount
        self.queryRecord(limitIndex)
        self.updateStatus()

    # 根据分页查询记录
    def queryRecord(self, limitIndex):
        sql = "SELECT * FROM user limit %d,%d" % (limitIndex, self.pageRecordCount)
        self.queryModel.setQuery(sql)

    # 更新空间状态
    def updateStatus(self):
        self.prevButton.setEnabled(False)

    # 界面关闭时关闭数据库连接
    def closeEvent(self, event):
        self.db.close()

    def initUI(self, Qmodelidx):
        # 每次点击清空右边窗口数据
        self.model02.clear()
        # 定义一个数组存储路径下的所有文件
        PathData = []
        # 获取双击后的指定路径
        filePath = self.model01.filePath(Qmodelidx)
        # List窗口文件赋值
        PathDataName = self.model02.invisibleRootItem()
        # 拿到文件夹下的所有文件
        PathDataSet = os.listdir(filePath)
        # 进行将拿到的数据进行排序
        PathDataSet.sort()
        # 遍历判断拿到的文件是文件夹还是文件，Flase为文件，True为文件夹
        for Data in range(len(PathDataSet)):
            if os.path.isdir(filePath + '\\' + PathDataSet[Data]) == False:
                PathData.append(PathDataSet[Data])
            elif os.path.isdir(filePath + '\\' + PathDataSet[Data]) == True:
                print('2')
        # 将拿到的所有文件放到数组中进行右边窗口赋值。
        for got in range(len(PathData)):
            gosData = QStandardItem(PathData[got])
            PathDataName.setChild(got, gosData)


class logindialog(QDialog, Ui_Load_lineEdit):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # super(logindialog, self).__init__(*args, **kwargs)
        self.setupUi(self)  ##初始化界面内容

        self.setWindowFlags(Qt.FramelessWindowHint)

        ## 绑定按钮事件
        self.pushButton_enter.clicked.connect(self.check_login_func)
        self.pushButton_close.clicked.connect(self.check_close_func)

    # 判断用户密码是否正确
    def check_close_func(self):
        self.close()

    # 判断用户密码是否正确
    def check_login_func(self):
        if USER_PWD2.get(self.lineEdit_user.text()) != self.lineEdit_password.text():
            QMessageBox.critical(self, 'Wrong', '用户名或密码错误!')
            return
        self.accept()
        self.lineEdit_user.clear()
        self.lineEdit_password.clear()


if __name__ == "__main__":
    app = QApplication(sys.argv)

    dialog = logindialog()
    # dialog.showMaximized()
    if dialog.exec_() == QDialog.Accepted:
        the_window = MainWindow()
        the_window.showMaximized()
        the_window.show()
    sys.exit(app.exec_())
